package com.it.rpc.core.client;

import com.alibaba.fastjson.JSON;
import com.it.rpc.IDL.user.UserResponseObj;
import com.it.rpc.core.codec.ResponseBody;
import com.it.rpc.core.protocol.Request;
import com.it.rpc.core.protocol.Response;
import com.sun.xml.internal.messaging.saaj.util.ByteInputStream;

import java.io.*;
import java.net.InetSocketAddress;
import java.net.Socket;

public class RpcClientTransport {


    // 发送请求 建立socket连接
    public Response send(Request request) {
        OutputStream SocketOutputStream = null;
        InputStream socketInputStream = null;
        try (Socket socket = new Socket("localhost", 9999)) {
            byte[] requestByte = JSON.toJSONBytes(request);
            //
            SocketOutputStream = socket.getOutputStream();
            socketInputStream = socket.getInputStream();

            // 包装socket输出流，便于传输对象
            SocketOutputStream.write(requestByte);
            SocketOutputStream.flush();


            byte[] bytes = new byte[1024 * 1024];
            int read = socketInputStream.read(bytes);
            Response response = (Response) JSON.parseObject(bytes, Response.class);
            if (response.getHeader().equals("version=1")) {
                return response;
            }


        } catch (IOException e) {
            e.printStackTrace();
        }

        return null;
    }
}
